package com.hujing.springsource.a02;

import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.Controller;

/**
 * 创建一些经典的ApplicationContext容器
 */
public class TestApplicationContext {

    public static void main(String[] args) {
        testAnnotationConfigServletWebServerApplicationContext();
    }

    public static void testAnnotationConfigServletWebServerApplicationContext() {
        //创建AnnotationConfigServletWebServerApplicationContext容器
        AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(WebConfig.class);
    }

    @Configuration
    public static class WebConfig{
        //注册tomcat容器
        @Bean
        public ServletWebServerFactory servletWebServerFactory() {
            return new TomcatServletWebServerFactory();
        }

        //注册dispatcherServlet
        @Bean
        public DispatcherServlet dispatcherServlet(){
            return new DispatcherServlet();
        }

        //将dispatcherServlet注册到tomcat容器中
        @Bean
        public DispatcherServletRegistrationBean registrationBean(DispatcherServlet dispatcherServlet){
            return new DispatcherServletRegistrationBean(dispatcherServlet,"/");
        }

        //定义一个接口
        @Bean("/hello")
        public Controller helloController(){
            return (request, response) -> {
                response.getWriter().println("hello");
                return null;
            };
        }
    }
}


